<template>
  <div class="wrapper">
    <div class="edit" @click="isDel = !isDel" v-if="goodsList.length > 0">
      {{ !isDel ? '编辑' : '完成' }}
    </div>
    <div class="cart" v-if="goodsList.length > 0">
      <div class="title">自营商品</div>
      <div class="item" v-for="(item, index) of goodsList" :key="index">
        <div class="pick" @click="buyPick(index)" v-show="!isDel">
          <div class="circle">
            <div class="inner" v-show="buyGoodsId.includes(index)"></div>
          </div>
        </div>
        <div class="pick" @click="delPick(index)" v-show="isDel">
          <div class="circle">
            <div class="inner" v-show="delGoodsId.includes(index)"></div>
          </div>
        </div>
        <div class="img">
          <img :src="item.url">
        </div>
        <div class="title">
          <h3>{{ item.title }}</h3>
          <h4 @click="getGuage(item.guid, index)">规格：{{ item.name }}</h4>
          <h5>￥{{ item.price }}</h5>
        </div>
        <div class="count">
          <CountCtrl :index="index" :count="item.num" :maxCount="item.stock" @change="countChange"></CountCtrl>
        </div>
      </div>
    </div>
    <div class="cart" v-else style="text-align: center;color:#666">
      您的购物车中没有商品
    </div>
    <div class="total">
      <div class="all" @click="buyPickAll" v-show="!isDel">
        <div class="circle">
          <div class="inner" v-show="isBuyAll"></div>
        </div>
        <span>全选</span>
      </div>
      <div class="all" @click="delPickAll" v-show="isDel">
        <div class="circle">
          <div class="inner" v-show="isDelAll"></div>
        </div>
        <span>全选</span>
      </div>
      <div class="price">
        <h3>合计: <span>{{ this.totalPrice | money }}</span></h3>
        <h5>不含运费</h5>
      </div>
      <div class="result success" v-show="!isDel" @click="buyAction">
        结算({{ totalCount }})
      </div>
      <div class="result" :class="{delete: delGoods.length > 0}" v-show="isDel" @click="delAction">
        删除
      </div>
    </div>
    <transition name="slide">
      <div class="slide-wrapper" v-if="show">
        <div class="title">
          <div class="img">
            <img :src="guageImage">
          </div>
          <div class="name">
            <h3>￥{{ guagePrice }}</h3>
            <h5>库存 {{ guageStock }} 件</h5>
          </div>
        </div>
        <p>规格</p>
        <div class="guage-list">
          <GuageList :guageList="guageList" :currentGuage="guage" @pickGuage="pickGuage"></GuageList>
        </div>
        <button class="btn" @click="guageConfirm">
          确定
        </button>
      </div>
    </transition>
    <Fade>
      <MaskView v-show="show" @click.native="show = false"></MaskView>
    </Fade>
  </div>
</template>

<script>
  import _ from 'lodash'
  import Fade from '@/components/fade/Fade.vue'
  import MaskView from '@/components/mask/Mask.vue'
  import CountCtrl from '@/components/countCtrl/CountCtrl.vue'
  import GuageList from '@/components/guageList/GuageList.vue'
  import { mapState } from 'vuex'
  export default {
    name: 'ShopCart',
    components: {
      Fade,
      MaskView,
      CountCtrl,
      GuageList
    },
    created() {
      this._getList()
    },
    data() {
      return {
        goodsList:[],
        buyGoodsId: [],
        delGoodsId: [],
        isDel: false,
        guageList: [],
        guage: '',
        guageImage: '',
        guagePrice: '',
        guageStock: '',
        cartId: '',
        show: false
      }
    },
    computed: {
      ...mapState(['openId']),
      buyGoods() {
        let arr = []
        this.buyGoodsId.forEach(item => {
          arr.push(this.goodsList[item])
        })
        return arr
      },
      delGoods() {
        let arr = []
        this.delGoodsId.forEach(item => {
          arr.push(this.goodsList[item])
        })
        return arr
      },
      isBuyAll() {
        return this.goodsList.length === this.buyGoodsId.length
      },
      isDelAll() {
        return this.goodsList.length === this.delGoodsId.length
      },
      totalCount() {
        let count = 0
        this.buyGoods.forEach(item => {
          count += Number(item.num)
        })
        return count
      },
      totalPrice() {
        let price = 0
        if(this.buyGoods.length > 0) {
          this.buyGoods.forEach(item => {
            price += Number(item.num) * Number(item.price)
          })
        }
        return price
      }
    },
    methods: {
      countChange: _.debounce(function (data) {
        this.goodsList[data.index].num = data.count
        this._AandR(data.count, data.index)
      }, 500),
      //加减购物车商品
      async _AandR(count, index) {
        this.$axios({
          url: '/v1/cart/num',
          method: 'POST',
          data: {
            openid: this.openId,
            id: this.goodsList[index].id,
            num: count
          }
        })
      },
      buyPick(index) {
        if(!this.buyGoodsId.includes(index)) {
          this.buyGoodsId.push(index)
        } else {
          this.buyGoodsId = this.buyGoodsId.filter(item => {
            return item != index
          })
        }
      },
      delPick(index) {
        if(!this.delGoodsId.includes(index)) {
          this.delGoodsId.push(index)
        } else {
          this.delGoodsId = this.delGoodsId.filter(item => {
            return item != index
          })
        }
      },
      buyPickAll() {
        if(this.isBuyAll) {
          this.buyGoodsId = []
        } else {
          this.buyGoodsId = []
          this.goodsList.forEach((item, index) => {
            this.buyGoodsId.push(index)
          })
        }
      },
      delPickAll() {
        if(this.isDelAll) {
          this.delGoodsId = []
        } else {
          this.delGoodsId = []
          this.goodsList.forEach((item, index) => {
            this.delGoodsId.push(index)
          })
        }
      },
      buyAction() {
        if(this.buyGoodsId.length == 0) {
          return
        }
        this.$store.commit('pushList', this.buyGoods)
        this.$router.push('/orderConfirm')
      },
      delAction() {
        if(this.delGoodsId.length == 0) {
          return
        }
        
        this._del()
      },
      async _getList() {
        try{
          let { data: {code, data} } = await this.$axios({
            url: '/v1/cart/list',
            method: 'GET',
            params: {
              openid: this.openId,
              size: 1000,
              current: 1
            }
          })
          if(code == 0) {
            this.goodsList = data.items.map(item => {
              item.num = Number(item.num)
              item.stock = Number(item.stock)
              if(item.num > item.stock) {
                item.num = item.stock
              }
              return item
            })
            if (this.goodsList.length<1) {
              this.isDel = false
            }
          } else {
            this.$bus.$emit('tip', data.message)
          }
        }catch(e){
          this.$bus.$emit('tip', e)
        }
      },
      //删除购物车
      async _del() {
        let arr = []
        arr = this.delGoods.map(item => {
          return item.id
        })
        try{
          let { data: {code, data} } = await this.$axios({
            url: '/v1/cart/single',
            method: 'POST',
            data: {
              openid: this.openId,
              id: arr.toString()
            }
          })
          if(code == 0) {
            this.delGoodsId = []
            this.buyGoodsId = []
            this._getList()
          } else {
            this.$bus.$emit('tip', data.message)
          }
        }catch(e){
          this.$bus.$emit('tip', e)
        }
      },
      //点击规格，请求该商品规格后，弹窗
      async getGuage(guageId, index) {
        /*
          // _getGuage()
          函数接受两个参数，当前规格id，这条数据的index
        */
        try{
          let { data: {code, data} } = await this.$axios({
            url: '/v1/goods/list',
            method: 'GET',
            params: {
              id: this.goodsList[index].goods_id,
              openid: this.openId
            }
          })
          if(code === 0) {
            let thisGuage = []
            this.guageList = data.gui.map(item => {
              item[0].price = item[0].price || item[0].m_price
              return item[0]
            })
            thisGuage = this.guageList.filter(item => {
              return item.id === guageId
            })
            this.guage = guageId
            this.cartId = this.goodsList[index].id
            this.guageImage = thisGuage[0].url
            this.guagePrice = thisGuage[0].price
            this.guageStock = thisGuage[0].stock
            this.show = true
          } else {
            this.$bus.$emit('tip', data.message)
          }
        }catch(e){
          this.$bus.$emit('tip', e)
        }
        
      },
      pickGuage(guage) {
        this.guage = guage.id
        this.guageImage = guage.url
        this.guagePrice = guage.price
        this.guageStock = guage.stock
      },
      async guageConfirm() {
        try{
          let { data: {code, data} } = await this.$axios({
            url: '/v1/cart/modify',
            method: "POST",
            data: {
              id: this.cartId,
              hao_id: this.guage,
              openid: this.openId
            }
          })
          if(code == 0) {
            this._getList()
            this.show = false
          } else {
            this.$bus.$emit('tip', data.message)
          }
        }catch(e){
          this.$bus.$emit('tip', e)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/assets/css/base.scss';
  .slide-enter, .slide-leave-to {
    transform: translate3d(0, 100%, 0);
  }
  .slide-enter-active, .slide-leave-active {
    transition: all 0.2s linear;
  }
  .wrapper {
    background: #eee;
    min-height:100vh;
    padding-bottom: 1.8rem;
  }
  .edit {
    font-size: 0.28rem;
    padding: 0.2rem;
    text-align: right;
    background: #eee;
  }
  .cart {
    font-size: 0.28rem;
    padding: 0.2rem;
    background: #fff;
  }
  .item {
    display: flex;
    position: relative;
    padding: 0.1rem;
    .pick {
      flex: 0 0 0.5rem;
      width: 0.5rem;
      position: relative;
      margin-right: 0.1rem;
      height: 1.5rem;
      .circle {
        position: absolute;
        @include center;
        width: 0.3rem;
        height: 0.3rem;
        border: 1px solid $colorGray;
        border-radius: 50%;
        .inner {
          position: absolute;
          @include center;
          width: 0.2rem;
          height: 0.2rem;
          background: $colorRed;
          border-radius: 50%;
        }
      }
    }
    .img {
      flex: 0 0 1.5rem;
      margin-right: 0.2rem;
      width: 1.5rem;
      height: 1.5rem;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .title {
      flex: 1;
      position: relative;
      height: 1.5rem;
      h3 {
        font-size: 0.28rem;
      }
      h4 {
        font-size: 0.24rem;
      }
      h5 {
        position: absolute;
        bottom: 0;
        font-size: 0.28rem;
        color: $colorRed;
      }
    } 
    .count {
      position: absolute;
      right: 0.1rem;
      bottom: 0.1rem;
    }
  }
  .total {
    display: flex;
    position: fixed;
    box-shadow: 0 0px 2px 0px #fff;
    width: 100%;
    bottom:50px;
    height: 0.8rem;
    background: #fff;
    .all {
      flex: 1;
      position: relative;
      padding: 0 0.2rem;
      line-height: 0.8rem;
      .circle {
        display: inline-block;
        position: relative;
        width: 0.3rem;
        height:0.3rem;
        border: 1px solid $colorGray;
        border-radius: 50%;
        vertical-align: middle;
        .inner {
          position: absolute;
          @include center;
          width: 0.2rem;
          height: 0.2rem;
          background: $colorRed;
          border-radius: 50%;
        }
      }
      span {
        display: inline-block;
        font-size: 0.28rem;
        margin-left: 0.2rem;
        vertical-align: middle;
      }
    }
    .price {
      flex: 1;
      padding-right:0.1rem;
      text-align: right;
      h3 {
        font-size: 0.28rem;
        span {
          color: $colorRed;
        }
      }
      h5 {
        font-size: 0.24rem;
        color: $colorGray;
      }
    }
    .result {
      flex: 0 0 1.6rem;
      width: 1.6rem;
      line-height: 0.8rem;
      color: #fff;
      background: #eee;
      text-align: center;
      font-size: 0.28rem;
      &.success {
        background: $colorRed;
      }
      &.delete {
        background: orange;
      }
    }
  }
  .slide-wrapper {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 7rem;
    background: #fff;
    z-index: 11;
    .title {
      display: flex;
      align-items: center;
      padding: 0.2rem;
      height: 2rem;
      border-bottom: 1px solid $bgGray;
      .img {
        flex: 0 0 1.6rem;
        margin-right: 0.2rem;
        width: 1.6rem;
        height: 1.6rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .name {
        flex: 1;
        h3 {
          color: $colorRed;
        }
      }
    }
    p {
      margin-top: 0.2rem;
      padding-left: 0.2rem;
      font-size: 0.28rem;
    }
    .guage-list {
      padding: 0.2rem;
    }
    .count {
      display: flex;
      padding: 0.2rem;
      align-items: center;
      .num {
        flex: 1;
        font-size: 0.28rem;
      }
      .ctrl {
        flex: 0 0 1.5rem;
      }
    }
    .btn {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 0.2rem;
      background: $colorRed;
      color: #fff;
      border: none;
      font-size: 0.28rem;
    }
  }
</style>
